from neo4j import GraphDatabase
from prefect import task
import json
from prefect.blocks.system import Secret

@task
def connect_to_neo4j(target, NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD, NEO4J_DATABASE):
    driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USERNAME, NEO4J_PASSWORD))
    # driver.verify_connectivity(database=database)
    with driver.session(database=NEO4J_DATABASE) as session:
        result = session.run("return true as success")
        for record in result:
            if record["success"]:
                print(f"connect target to `{target}` is ok")
                

@task
def get_config_from_secret_block_as_json(block_name):
    """
    get config from remote secret block
    """
    try:
        secret_block = Secret.load(block_name)
        # Access the stored secret
        json_str = secret_block.get()
        # print(f"secret str:'{json_str}'")
        config = json.loads(json_str) if json_str else {}
        return config
    except ValueError as err:
        print(f"secret block `{block_name}` is not found!!", err)
    except Exception as err:
        print("Something else went wrong", err)

    return {}